<template>
  <!-- 用户管理 -->
  <div style="position: relative;">
    <el-card style="height:calc( 100vh - 85px); overflow:auto; ">
      <!-- 信息搜索框 -->
      <userManageFrom :query-obj="queryObj" @queryClickfn="queryClick" @resetQueryfn="resetQuery" />
      <!-- 调整状态按钮 -->
      <el-row style="margin-bottom:10px">
        <div style="float:left">
          <el-button type="primary" plain @click="addUserClick">
            <i class="el-icon-plus" />
            {{ $t('button.AddUser') }}
          </el-button>
          <el-button type="primary" plain @click="OnlineUsersClick">在线用户</el-button>
          <el-button type="primary" plain @click="JobClick">查看职位</el-button>
        </div>
      </el-row>

      <!-- 任务总表 -->
      <el-table
        v-loading="listLoading"
        :data="tableData"
        border
        height="calc( 100vh - 280px)"
        :row-style="{height:'40px'}"
        :cell-style="{padding:'0px'}"
        style="width: 100%;  margin-bottom: 10px;overflow:auto;"
      >
        <el-table-column prop="userName" :label="$t('text.UserName')" />
        <el-table-column prop="userNo" :label="$t('text.UserNo')" />
        <el-table-column prop="roles" :label="$t('text.Role')" show-overflow-tooltip>
          <template slot-scope="scope">
            <div>{{ getRoleName(scope.row) }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="depts" label="部门" show-overflow-tooltip>
          <template slot-scope="scope">
            <div>{{ getDeptsName(scope.row) }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="job" label="职位" />
        <el-table-column prop="tel" label="电话" width="120" />
        <el-table-column prop="mailAccount" label="邮箱" width="180" />
        <el-table-column prop="extends" label="扩展" width="80" align="center">
          <template slot-scope="scope">
            <el-button type="text" @click="detailsClick(scope.row)">详情</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="enabled" label="是否禁用" width="100" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.enabled?$t('button.Enabled'):$t('button.Disabled') }}</span>
          </template>
        </el-table-column>
        <el-table-column width="150" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="editUserClick(scope.row)"
            >{{ $t('button.Edit') }}</el-button>
            <el-button
              type="text"
              size="small"
              @click="deleteUserClick(scope.row)"
            >{{ $t('button.Delete') }}</el-button>
            <el-button
              type="text"
              size="small"
              @click="changePasswordClick(scope.row)"
            ><div style="color:blue">修改密码</div></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <paging
        :pagion-obj="pagionObj"
        :handle-size-change="handleSizeChange"
        :handle-page-change="handlePageChange"
      />
    </el-card>
    <!-- 修改密码 -->
    <el-dialog :visible.sync="changePasswordDialog" :modal-append-to-body="false">
      <el-form
        ref="editPassword"
        :model="changePasswordData"
        :rules="passwordrules"
        size="small"
        label-width="100px"
      >
        <el-form-item :label="$t('text.UserName')">
          <span>{{ changePasswordData.userName }}</span>
        </el-form-item>
        <el-form-item :label="$t('text.UserNo')">
          <span>{{ changePasswordData.userNo }}</span>
        </el-form-item>
        <el-form-item :label="$t('text.Password')" prop="password">
          <el-input v-model.trim="changePasswordData.password" show-password :placeholder="$t('text.Password')" />
        </el-form-item>
        <el-form-item :label="$t('text.CheckPassword')" prop="changeCheckPassword">
          <el-input v-model.trim="changePasswordData.changeCheckPassword" show-password :placeholder="$t('text.CheckPassword')" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" plain size="medium" @click="PasswordChange">{{ $t('button.Change') }}</el-button>
          <el-button size="medium" @click="changePasswordClose">{{ $t('button.Cancel') }}</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 添加用户的dialog -->
    <el-dialog
      :title="dialogName"
      top="5vh"
      width="40%"
      :before-close="handleClose"
      :visible.sync="UserManageVisible"
    >
      <el-form
        ref="userAddData"
        :model="userAddData"
        :rules="rules"
        size="small"
        label-width="100px"
      >
        <el-form-item :label="$t('text.UserName')" prop="userName">
          <el-input v-model.trim="userAddData.userName" :placeholder="$t('text.UserName')" />
        </el-form-item>
        <el-form-item :label="$t('text.UserNo')" prop="userNo">
          <el-input v-model.trim="userAddData.userNo" :placeholder="$t('text.UserNo')" />
        </el-form-item>
        <el-form-item :label="$t('text.Password')" prop="password">
          <el-input
            v-model.trim="userAddData.password"
            show-password
            :placeholder="$t('text.Password')"
          />
        </el-form-item>
        <el-form-item :label="$t('text.CheckPassword')" prop="checkPassword">
          <el-input
            v-model.trim="userAddData.checkPassword"
            show-password
            :placeholder="$t('text.CheckPassword')"
          />
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model.trim="userAddData.tel" placeholder="电话" />
        </el-form-item>
        <el-form-item label="邮箱" prop="mailAccount">
          <el-input v-model.trim="userAddData.mailAccount" placeholder="邮箱" />
        </el-form-item>
        <el-form-item label="职位">
          <el-select v-model="userAddData.job">
            <el-option
              v-for="item in jobList"
              :key="item.id"
              :value="item.jobName"
              :label="item.jobName"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" plain size="medium" @click="addUserConfirm">{{ $t('button.Confirm') }}</el-button>
          <el-button size="medium" @click="handleClose">{{ $t('button.Cancel') }}</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 编辑用户的dialog -->
    <el-dialog
      :title="dialogName"
      top="5vh"
      width="40%"
      :before-close="handleClose"
      :visible.sync="UpdateUserVisible"
    >
      <el-form
        ref="userUpdateData"
        :model="userUpdateData"
        :rules="rules"
        size="small"
        label-width="100px"
      >
        <el-form-item :label="$t('text.UserNo')" prop="userNo">{{ userUpdateData.userNo }}</el-form-item>
        <el-form-item :label="$t('text.UserName')" prop="userName">
          <el-input v-model.trim="userUpdateData.userName" :placeholder="$t('text.UserName')" />
        </el-form-item>
        <!-- <el-form-item v-if="changePassword" :label="$t('text.Password')" prop="password">
          <el-input
            v-model.trim="userUpdateData.password"
            show-password
            :placeholder="$t('text.Password')"
          />
        </el-form-item>
        <el-form-item
          v-if="changePassword"
          :label="$t('text.CheckPassword')"
          prop="UpdateCheckPassword"
        >
          <el-input
            v-model.trim="userUpdateData.UpdateCheckPassword"
            show-password
            :placeholder="$t('text.CheckPassword')"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            v-if="!changePassword"
            @click="changePassword = true"
          >{{ $t('button.ChangePassword') }}</el-button>
        </el-form-item> -->
        <el-form-item label="电话">
          <el-input v-model.trim="userUpdateData.tel" placeholder="电话" />
        </el-form-item>
        <el-form-item label="邮箱" prop="mailAccount">
          <el-input v-model.trim="userUpdateData.mailAccount" placeholder="邮箱" />
        </el-form-item>
        <el-form-item :label="$t('text.Role')">
          <el-tree
            ref="Roletree"
            style="background-color:#eee;height:150px;overflow: auto;"
            :data="roleList"
            show-checkbox
            node-key="id"
            :props="defaultProps"
            @check="handleCheck"
          />
        </el-form-item>
        <el-form-item label="部门">
          <el-tree
            ref="depttree"
            style="background-color:#eee;height:150px;overflow: auto;"
            :data="deptList"
            show-checkbox
            node-key="id"
            check-strictly
            accordion
            :props="deptdefaultProps"
            @check="depthandleCheck"
          />
        </el-form-item>
        <el-form-item label="职位">
          <el-select v-model="userUpdateData.job">
            <el-option
              v-for="item in jobList"
              :key="item.id"
              :value="item.jobName"
              :label="item.jobName"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="editdialogbutton" :label="$t('text.IsDisabled')">
          <el-switch
            v-model="userUpdateData.enabled"
            :active-text="$t('button.Enabled')"
            :inactive-text="$t('button.Disabled')"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          plain
          size="medium"
          @click="editUserConfirm"
        >{{ $t('button.Change') }}</el-button>
        <el-button size="medium" @click="handleClose">{{ $t('button.Cancel') }}</el-button>
      </span>
    </el-dialog>
    <!-- OnlineUsers -->
    <el-dialog title="OnlineUsers" top="3vh" width="1300px" :visible.sync="OnlineUsersDialog">
      <el-table
        :data="OnlineUsersData"
        border
        height="calc( 100vh - 275px)"
        :row-style="{height:'40px'}"
        :cell-style="{padding:'0px'}"
        style="width: 100%;  margin-bottom: 10px;overflow:auto;"
      >
        <el-table-column prop="userName" :label="$t('text.UserName')" />
        <el-table-column prop="userNo" :label="$t('text.UserNo')" />
        <el-table-column prop="ip" label="ip" />
        <el-table-column prop="createTime" :label="$t('text.createTime')" width="160">
          <template slot-scope="scope">
            <span>{{ scope.row.createTime | formatDate }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="lastUpdateTime" :label="$t('text.LastUpdateTime')" width="160">
          <template slot-scope="scope">
            <span>{{ scope.row.lastUpdateTime }}</span>
          </template>
        </el-table-column>-->
        <el-table-column>
          <template slot-scope="scope">
            <el-button type="text" @click="LotoutClick(scope.row)">{{ $t('button.offLine') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 查看职位 -->
    <el-dialog title="职位" top="3vh" width="500px" :visible.sync="JobDialog">
      <el-button type="primary" plain size="mini" @click="addMenu">
        <i class="el-icon-plus" /> 新增职位
      </el-button>
      <el-table :data="jobList" border style="width: 100%; margin-bottom: 10px;margin-top:10px;">
        <el-table-column prop="jobName" label="职位" />
        <el-table-column width="100">
          <template slot-scope="scope">
            <el-button
              size="small"
              type="text"
              @click="deleteJobClick(scope.row)"
            >{{ $t('button.Delete') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 新增职位 -->
    <el-dialog :visible.sync="jobAddDialog" width="500px">
      <el-form v-model="JobAddData" size="mini" label-width="100px">
        <el-form-item label="职位名">
          <el-input v-model.trim="JobAddData.jobName" placeholder="职位名" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addJobClick">{{ $t('button.Add') }}</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 扩展弹窗 -->
    <el-dialog :visible.sync="detailsDialog" width="500px">
      <el-button type="primary" plain size="mini" @click="addExtendsClick">
        <i class="el-icon-plus" /> 新增扩展
      </el-button>
      <el-table
        :data="extendsList"
        border
        style="width: 100%; margin-bottom: 10px;margin-top:10px;"
      >
        <el-table-column prop="key" label="key" />
        <el-table-column prop="value" label="value" />
        <el-table-column width="100">
          <template slot-scope="scope">
            <el-button size="small" type="text" @click="editExtendsClick(scope.row)">编辑</el-button>
            <el-button
              size="small"
              type="text"
              @click="deleteExtendsClick(scope.row)"
            >{{ $t('button.Delete') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <!-- 编辑扩展 -->
    <el-dialog title="编辑扩展" :visible.sync="editExtendsDialog" width="30%" top="5vh">
      <p v-for="(item, key) in editExtendsData" :key="key">
        <template v-if="key === 'value' ">
          <span style="display:inline-block;width: 30%;">{{ key }}</span>
          <el-input v-model="editExtendsData[key]" :placeholder="item" style="width:70%" />
        </template>
      </p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editExtendsDialog = false">{{ $t('button.Cancel') }}</el-button>
        <el-button type="primary" @click="editExtendsConfirm">{{ $t('button.Confirm') }}</el-button>
      </span>
    </el-dialog>

    <!-- 新增扩展 -->
    <el-dialog title="新增扩展" :visible.sync="addExtendsDialog" width="30%" top="5vh">
      <el-form v-model="addExtendsData" size="mini" label-width="100px">
        <el-form-item label="key">
          <el-input v-model.trim="addExtendsData.key" placeholder="key" />
        </el-form-item>
        <el-form-item label="value">
          <el-input v-model.trim="addExtendsData.value" placeholder="value" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addExtendsDialog = false">{{ $t('button.Cancel') }}</el-button>
        <el-button type="primary" @click="addExtendsConfirm">{{ $t('button.Confirm') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  queryUserApi,
  addUserApi,
  queryRoleApi,
  getJobApi,
  GetTreeDept,
  deleteUserApi,
  editUserApi,
  SetPassword,
  AddUserRoleApi,
  RemoveUserRoleApi,
  AddUserDept,
  RemoveDept,
  GetOnlineUsers,
  AddJobApi,
  LogoutF,
  DeleteJobApi,
  AddExt,
  DeleteExtendApi,
  UpdateExtendApi
} from '@/api/manage'
import { Message } from 'element-ui'
import permission from '@/permission/index.js' // 权限判断指令
import userManageFrom from './components/userManageFrom.vue'
export default {
  name: 'UserManage',
  directives: { permission },
  components: {
    userManageFrom
  },
  data() {
    // 密码的自定义校验
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (value.length < 6) {
          callback(new Error('密码不能小于6位'))
        } else {
          callback()
        }
      }
    }
    // 确认密码的自定义校验
    var validatCheckePass = (rule, value, callback) => {
      if (value !== this.userAddData.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    // 确认密码的自定义校验
    var UpdatevalidatCheckePass = (rule, value, callback) => {
      if (value !== this.userUpdateData.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    // 确认密码的自定义校验
    var changevalidatCheckePass = (rule, value, callback) => {
      if (value !== this.changePasswordData.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      queryObj: {
        // userNo: '', // 用户名
        userName: '', // 账号
        job: '', // 角色
        page: 0, // 第几页
        size: 0 // 每页条数
      },
      // 分页的数据
      pagionObj: {
        size: 10,
        currentPage: 1,
        total: 100
      },
      // 请求返回的数据
      tableData: [],
      tableDataAll: [],
      isopen: false,
      // 页面loding效果
      listLoading: true,
      listLoading2: true,
      // dialog名
      dialogName: '添加用户',
      // 添加dialog按钮
      adddialogbutton: false,
      // 编辑dialog按钮
      editdialogbutton: false,
      // UserManage的dialog显示
      UserManageVisible: false,
      // 在线用户数据及弹窗
      OnlineUsersData: [],
      OnlineUsersDialog: false,
      // 职位的数据及弹窗
      JobDialog: false,
      jobAddDialog: false,
      JobAddData: {
        jobName: ''
      },
      // 扩展的数据及弹窗
      extendsList: [],
      extendsData: {},
      detailsDialog: false,
      editExtendsDialog: false,
      editExtendsData: {
        key: '',
        value: '',
        userId: 0,
        id: 0
      },
      addExtendsDialog: false,
      addExtendsData: {
        key: '',
        value: '',
        id: 0
      },
      // 编辑用户的弹窗及数据
      UpdateUserVisible: false,
      userUpdateData: {
        depts: [],
        userNo: '',
        userName: '',
        password: '',
        tel: '',
        mailAccount: '',
        UpdateCheckPassword: '',
        job: '',
        isLeader: true,
        enabled: true
      },
      editData: {},
      // 角色列表数据
      roleList: [],
      deptList: [],
      // 职位列表
      jobList: [],
      // 修改角色
      UpdateRole: [],
      Updatedept: [],
      // 修改密码框是否显示
      changePassword: false,
      // 添加用户的数据
      userAddData: {
        userNo: '',
        userName: '',
        tel: '',
        mailAccount: '',
        password: '',
        // 确认密码
        checkPassword: '',
        job: '-'
      },
      // 修改密码
      changePasswordDialog: false,
      changePasswordData: {
        password: null,
        changeCheckPassword: null
      },
      // 树形数据转换
      defaultProps: {
        children: 'children',
        label: 'roleName'
      },
      deptdefaultProps: {
        children: 'child',
        label: 'deptName'
      },
      // 表单校验
      rules: {
        userNo: [
          { required: true, message: '必填哦！', trigger: ['blue', 'change'] }
        ],
        userName: [
          { required: true, message: '必填哦！', trigger: ['blue', 'change'] }
        ],
        password: [
          { required: true, message: '必填哦！', trigger: ['blue', 'change'] },
          { validator: validatePass, trigger: ['blue', 'change'] }
        ],
        checkPassword: [
          { required: true, message: '必填哦！', trigger: ['blue', 'change'] },
          { validator: validatCheckePass, trigger: ['blue', 'change'] }
        ],
        UpdateCheckPassword: [
          { required: true, message: '必填哦！', trigger: ['blue', 'change'] },
          { validator: UpdatevalidatCheckePass, trigger: ['blue', 'change'] }
        ],
        roleName: [
          { required: true, message: '请选择好角色', trigger: ['blue'] }
        ],
        mailAccount: [
          { required: true, message: '必填哦！', trigger: ['blue', 'change'] }
        ]
      },
      passwordrules: {
        password: [
          { required: true, message: '必填哦！', trigger: ['blue', 'change'] },
          { validator: validatePass, trigger: ['blue', 'change'] }
        ],
        changeCheckPassword: [
          { required: true, message: '必填哦！', trigger: ['blue', 'change'] },
          { validator: changevalidatCheckePass, trigger: ['blue', 'change'] }
        ]
      },
      // 列位置数据
      deleteCell: {
        isuserNo: true,
        isuserName: true,
        isroleName: true,
        isenabled: true,
        isoperate: true
      },
      // excel 数据的key 表头数据
      headersArr: ['用户名', '账号', '角色', '状态'],
      // 将表头转换成中文
      headersRelations: {
        用户名: 'userNo',
        账号: 'userName',
        角色: 'roleName',
        状态: 'enabled'
      }
    }
  },
  // 监视时间变化
  watch: {
    timestart_end(newData) {
      if (newData !== null && newData.length > 0) {
        this.queryObj.startTime = this.timestart_end[0]
        this.queryObj.endTime = this.timestart_end[1]
      } else {
        this.queryObj.startTime = '0001/1/1 0:00:00'
        this.queryObj.endTime = '0001/1/1 0:00:00'
      }
    }
  },
  created() {
    this.getRoleData()
  },
  mounted() {
    this.queryData()
  },
  methods: {
    /** 获取页面数据*/
    async queryData() {
      this.listLoading = true
      this.queryObj.size = this.pagionObj.size
      this.queryObj.page = this.pagionObj.currentPage
      const res = await queryUserApi(this.queryObj)
      this.tableData = res.data.data
      this.pagionObj.pageCount = res.data.pageCount
      this.pagionObj.total = res.data.count
      this.listLoading = false
    },
    // 获取角色
    async getRoleData() {
      const res = await queryRoleApi(this.queryObj)
      this.roleList = res.data.data
      // console.log(this.roleList)
      const res2 = await getJobApi()
      this.jobList = res2.data.data
      const res3 = await GetTreeDept()
      this.deptList = res3.data.data
    },
    // 搜索按钮
    queryClick() {
      this.pagionObj.currentPage = 1
      this.queryData()
    },
    // 刷新按钮
    refreshClick() {
      this.listLoading = true
      this.queryData()
      this.listLoading = false
    },
    /** 每页显示数据变化*/
    handleSizeChange(val) {
      this.pagionObj.size = val
      this.queryData()
    },
    /** 当前页变化*/
    handlePageChange(val) {
      this.pagionObj.currentPage = val
      this.queryData()
    },
    // 重置按钮
    resetQuery() {
      this.queryObj.job = ''
      this.queryObj.userName = ''
      // this.queryObj.roleName = 0
    },
    // 查看职位
    JobClick() {
      this.JobDialog = true
    },
    // 新增职位
    addMenu() {
      this.jobAddDialog = true
      this.JobAddData = {
        jobName: ''
      }
    },
    // 删除角色
    deleteJobClick(data) {
      this.$confirm('确认删除该职位吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await DeleteJobApi({ id: data.id })
          Message.success('删除成功')
          this.getRoleData()
        })
        .catch(() => {})
    },
    // 新增角色确认按钮
    async addJobClick() {
      if (this.JobAddData.jobName === '') {
        return Message.error('职位名不能为空')
      }
      await AddJobApi({
        jobName: this.JobAddData.jobName
      })
      Message.success(this.$t('text.OperateSuccessfully'))
      this.getRoleData()
      this.JobAddData = {
        jobName: ''
      }
      this.jobAddDialog = false
    },
    // 在线用户按钮
    async OnlineUsersClick() {
      const res = await GetOnlineUsers()
      this.OnlineUsersData = res.data.data
      console.log(res.data.data)
      this.OnlineUsersDialog = true
    },
    // 退出
    async LotoutClick(data) {
      this.$confirm(
        this.$t('text.Areyousuretoperformthisoperation'),
        this.$t('text.tip'),
        {
          confirmButtonText: this.$t('button.Confirm'),
          cancelButtonText: this.$t('button.Cancel'),
          type: 'warning'
        }
      ).then(async() => {
        await LogoutF({
          userNo: data.userNo
        })
        Message.success(this.$t('text.OperateSuccessfully'))
        setTimeout(() => {
          this.OnlineUsersClick()
        }, 1000)
      })
    },
    // 详情
    detailsClick(data) {
      this.extendsList = data.extends
      this.extendsData = data
      this.detailsDialog = true
    },
    // 新增扩展
    async addExtendsClick() {
      this.addExtendsDialog = true
      this.addExtendsData.id = this.extendsData.id
      this.addExtendsData.key = ''
      this.addExtendsData.value = ''
    },
    async addExtendsConfirm() {
      console.log({
        id: this.addExtendsData.id,
        key: this.addExtendsData.key,
        value: this.addExtendsData.value
      })
      await AddExt({
        id: this.addExtendsData.id,
        key: this.addExtendsData.key,
        value: this.addExtendsData.value
      })
      Message.success(this.$t('text.OperateSuccessfully'))
      const res = await queryUserApi(this.queryObj)
      res.data.data.forEach(item => {
        if (item.id === this.addExtendsData.id) {
          this.extendsList = item.extends
        }
      })
      this.tableData = res.data.data
      this.addExtendsDialog = false
    },
    // 编辑扩展
    async editExtendsClick(data) {
      this.editExtendsData.key = data.key
      this.editExtendsData.value = data.value
      this.editExtendsData.userId = data.userId
      this.editExtendsData.id = data.id
      this.editExtendsDialog = true
    },
    // 编辑扩展的确认
    async editExtendsConfirm() {
      await UpdateExtendApi({
        id: this.editExtendsData.id,
        value: this.editExtendsData.value
      })
      Message.success(this.$t('text.OperateSuccessfully'))
      const res = await queryUserApi(this.queryObj)
      res.data.data.forEach(item => {
        if (item.id === this.editExtendsData.userId) {
          this.extendsList = item.extends
        }
      })
      this.tableData = res.data.data
      this.editExtendsDialog = false
      this.addExtendsData.value = ''
    },
    // 删除扩展
    deleteExtendsClick(data) {
      this.$confirm('确认删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await DeleteExtendApi({ id: data.id })
        const res = await queryUserApi(this.queryObj)
        res.data.data.forEach(item => {
          if (item.id === data.userId) {
            this.extendsList = item.extends
          }
        })
        this.queryData()
        Message.success('删除成功')
      })
    },
    // 添加用户
    addUserClick() {
      this.dialogName = '添加用户'
      this.editdialogbutton = false
      this.UserManageVisible = true
      this.adddialogbutton = true
    },
    // 添加用户确认按钮
    addUserConfirm() {
      this.$refs.userAddData.validate(async valid => {
        if (valid) {
          await addUserApi({
            userNo: this.userAddData.userNo,
            userName: this.userAddData.userName,
            password: this.userAddData.password,
            job: this.userAddData.job,
            tel: this.userAddData.tel,
            mailAccount: this.userAddData.mailAccount,
            isLeader: true
          })
          this.queryData()
          this.UserManageVisible = false
          this.$refs.userAddData.resetFields()
          Message.success('创建成功')
        } else {
          Message.error('数据输入有误')
          return false
        }
      })
    },
    // 获取用户的角色
    getRoleName(data) {
      // console.log(data)
      const label = []
      data.roles.forEach(item => {
        label.push(item.roleName)
      })
      return label.join(' | ')
    },
    // 获取用户的部门
    getDeptsName(data) {
      // console.log(data)
      const label = []
      data.depts.forEach(item => {
        label.push(item.deptName)
      })
      return label.join(' | ')
    },
    // 编辑用户
    editUserClick(data) {
      // console.log(data)
      this.dialogName = '编辑用户'
      this.adddialogbutton = false
      this.UpdateUserVisible = true
      this.editdialogbutton = true
      this.editData = data
      this.userUpdateData.id = data.id
      this.userUpdateData.userNo = data.userNo
      this.userUpdateData.userName = data.userName
      this.userUpdateData.job = data.job
      this.userUpdateData.isLeader = data.isLeader
      this.userUpdateData.enabled = data.enabled
      this.userUpdateData.tel = data.tel
      this.userUpdateData.mailAccount = data.mailAccount
      if (this.changePassword) {
        this.userUpdateData.password = data.password
      }
      if (data.roles) {
        const role = []
        data.roles.forEach(item => {
          role.push(item.id)
        })
        this.UpdateRole = role
        this.$nextTick(() => {
          this.$refs.Roletree.setCheckedKeys(this.UpdateRole, true)
        })
        // console.log(this.UpdateRole, 'this.UpdateRole')
      }
      if (data.depts) {
        const dept = []
        data.depts.forEach(item => {
          dept.push(item.id)
        })
        this.Updatedept = dept
        this.$nextTick(() => {
          this.$refs.depttree.setCheckedKeys(this.Updatedept, true)
        })
        // console.log(this.Updatedept, 'this.Updatedept')
      }
    },
    // 编辑确认更新用户
    editUserConfirm() {
      this.$refs.userUpdateData.validate(async valid => {
        if (valid) {
          await editUserApi(this.userUpdateData)
          Message.success(this.$t('text.OperateSuccessfully'))
          this.queryData()
          this.UpdateUserVisible = false
        } else {
          Message.error('数据输入有误')
          return false
        }
      })
    },
    async handleCheck(data1, data2) {
      // console.log(data1, data2, this.editData)
      const arr = []
      this.editData.roles.forEach(item => {
        if (item) {
          arr.push(item.id)
        }
      })
      if (data2.checkedKeys.indexOf(data1.id) === -1) {
        // console.log(arr, this.editData, data1.id)
        await RemoveUserRoleApi({ userId: this.editData.id, roleId: data1.id })
        this.queryData()
        Message.success('操作成功')
      } else {
        await AddUserRoleApi({ userId: this.editData.id, roleId: data1.id })
        this.queryData()
        Message.success('操作成功')
      }
    },
    async depthandleCheck(data1, data2) {
      console.log(data1, data2, this.editData)
      const arr = []
      this.editData.roles.forEach(item => {
        if (item) {
          arr.push(item.id)
        }
      })
      if (data2.checkedKeys.indexOf(data1.id) === -1) {
        // console.log(arr, this.editData, data1.id)
        await RemoveDept({ userId: this.editData.id, deptId: data1.id })
        this.queryData()
        Message.success('操作成功')
      } else {
        await AddUserDept({ userId: this.editData.id, deptId: data1.id })
        this.queryData()
        Message.success('操作成功')
      }
    },
    // 删除用户
    async deleteUserClick(data) {
      const id = data.id
      this.$confirm('确认删除当前用户吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await deleteUserApi({ id })
          this.queryData()
          Message.success('操作成功')
        })
        .catch(() => {})
    },
    // 修改密码
    changePasswordClick(data) {
      this.changePasswordData.userName = data.userName
      this.changePasswordData.userNo = data.userNo
      this.changePasswordData.id = data.id
      this.changePasswordDialog = true
    },
    // 修改
    PasswordChange() {
      this.$refs.editPassword.validate(async(valid) => {
        if (valid) {
          if (this.changePasswordData.password === this.changePasswordData.changeCheckPassword) {
            await SetPassword({
              'id': this.changePasswordData.id,
              'password': this.changePasswordData.password
            })
            Message.success(this.$t('text.OperateSuccessfully'))
            this.changePasswordDialog = false
          } else {
            Message.error('两次输入密码不一致')
          }
        } else {
          Message.error('数据输入有误')
          return false
        }
      })
    },
    // 取消
    changePasswordClose() {
      this.changePasswordDialog = false
      this.changePasswordData.password = ''
      this.changePasswordData.checkPassword = ''
    },
    // 关闭dialog
    handleClose() {
      // 添加dialog按钮
      this.adddialogbutton = false
      // 编辑dialog按钮
      this.editdialogbutton = false
      // UserManage的dialog显示
      this.UserManageVisible = false
      // 修改密码框是否显示
      this.changePassword = false
      this.userAddData = {
        userNo: '',
        userName: '',
        password: '',
        checkPassword: '',
        tel: '',
        mailAccount: '',
        job: '',
        enabled: true
      }
      this.UpdateUserVisible = false
      this.userUpdateData = {
        userNo: '',
        userName: '',
        password: '',
        UpdateCheckPassword: '',
        job: '',
        tel: '',
        mailAccount: '',
        isLeader: true,
        enabled: true
      }
      this.UpdateRole = []
      this.Updatedept = []
    },
    // excel导出全部
    async exportAll() {
      const res2 = await queryUserApi({ size: 10000 })
      this.tableDataAll = res2.data.data
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
